/* 发送端代码 send.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define GROUP_IP "239.0.0.1"    // 组播组IP地址
#define PORT 8888               // 端口号
#define MSG "Hello, Multicast!" // 发送的消息

int main()
{
    int sockfd;
    struct sockaddr_in group_addr;
    char message[1024] = MSG;
    int opt = 1;

    // 创建UDP套接字
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置套接字选项，允许发送组播数据包
    if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &opt, sizeof(opt)) < 0)
    {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }

    // 设置组播地址和端口
    memset(&group_addr, 0, sizeof(group_addr));
    group_addr.sin_family = AF_INET;
    group_addr.sin_port = htons(PORT);
    group_addr.sin_addr.s_addr = inet_addr(GROUP_IP);

    // 发送组播消息
    printf("Sending multicast message: %s\n", message);
    if (sendto(sockfd, message, strlen(message), 0,
               (struct sockaddr *)&group_addr, sizeof(group_addr)) < 0)
    {
        perror("sendto failed");
        exit(EXIT_FAILURE);
    }

    printf("Message sent successfully.\n");
    close(sockfd);
    return 0;
}